package cn.lili.modules.supplier.serviceimpl;

import cn.lili.cache.Cache;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.StringUtils;
import cn.lili.modules.order.order.client.OrderClient;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.supplier.service.SupplierOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class SupplierOrderServiceImpl implements SupplierOrderService {


    private final OrderClient orderClient;

    private final RedisTemplate redisTemplate;

    @Override
    public Order cancel(String orderSn, String reason) {
//        Object orderSnVal = redisTemplate.boundValueOps("cancel-supplier::" + orderSn).get();
        //同一个订单，不是第一次请求，直接打回
//        if (orderSnVal != null && StringUtils.isNotEmpty((String) orderSnVal)) {
//            throw new ServiceException("重复请求");
//        }
//        redisTemplate.boundValueOps("cancel-supplier::" + orderSn).set(orderSn);
//        redisTemplate.expire("cancel-supplier::" + orderSn, 30, TimeUnit.MINUTES);

        Order order = orderClient.getBySn(orderSn);

        if (order.getSupplierId().equals(UserContext.getCurrentId())) {
            return orderClient.cancel(orderSn, reason);
        } else {
            throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR);
        }
    }

    @Override
    public Order delivery(String orderSn, String invoiceNumber, String logisticsId) {

        Order order = orderClient.getBySn(orderSn);

        if (order.getSupplierId().equals(UserContext.getCurrentId())) {

            return orderClient.delivery(orderSn, invoiceNumber, logisticsId);
        } else {
            throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR);
        }
    }
}
